package com.jiangjiang.eshop.order.price.v1.calculator.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiangjiang.eshop.order.dto.OrderItemDTO;
import com.jiangjiang.eshop.order.dto.PromotionActivityResult;
import com.jiangjiang.eshop.order.price.v1.calculator.PromotionActivityCalculator;
import com.jiangjiang.eshop.promotion.dto.PromotionActivityDTO;
import org.springframework.stereotype.Component;

/**
 * @Author Jianghaowen
 * @Date 2021/7/14
 * @Description: 满减类型的促销活动价格计算组件
 * @Version V1.0
 **/
@Component
public class ReachDiscountPromotionActivityCalculator implements PromotionActivityCalculator {
    /**
     * 优惠计算
     *
     * @param item              订单条目
     * @param promotionActivity 促销活动
     * @return
     * @throws Exception
     */
    @Override
    public PromotionActivityResult calculate(OrderItemDTO item, PromotionActivityDTO promotionActivity) throws Exception {
        double totalPrice = item.getPurchaseQuantity() * item.getPurchasePrice();
        String rulesJson = promotionActivity.getRule();
        JSONArray rules = JSONArray.parseArray(rulesJson);
        PromotionActivityResult result = PromotionActivityResult.builder().build();
        for (int i = 0; i < rules.size(); i++) {
            JSONObject jsonObject = rules.getJSONObject(i);
            Double thresholdAmount = jsonObject.getDouble("thresholdAmount");
            Double reduceAmount = jsonObject.getDouble("reduceAmount");

            if (totalPrice > thresholdAmount) {
                result.setDiscountAmount(reduceAmount);
                return result;
            }

        }
        return result;
    }
}
